package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.entity.SpcyRsZck;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.ISpcyRsZckService;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.spcyApi.utils.MyExcelUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.spcyApi.vo.common.HttpResultVo;
import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.PageVo;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Description: 审评查验-职称系列库
 * @Author: hua
 * @Date: 2024-01-11
 * @Version: V1.0
 */
@Api(tags = "技术职称系列系列库接口")
@RestController
@RequestMapping("/api/spzx-spcy/zcxl")
public class SpcyRsZckController {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsZckController.class);

    @Resource
    private ISpcyRsZckService spcyRsZckService;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Log(title = "技术职称系列库-分页列表查询")
    @ApiOperation(value = "技术职称系列库-分页列表查询")
    @GetMapping(value = "/pageList")
    public HttpResult<?> queryPageList(SpcyRsZck query, PageVo pageVo, OrderItemVo orderItemVo) {

        return HttpResult.ok(spcyRsZckService.selectPageList(query, pageVo, orderItemVo));
    }

    @Log(title = "技术职称系列库列表")
    @ApiOperation(value = "技术职称系列库列表")
    @GetMapping(value = "/list")
    public HttpResult<?> queryList(SpcyRsZck query) {

        return HttpResultVo.HttpResultList(spcyRsZckService.selectList(query));
    }

    @Log(title = "技术职称系列库-添加")
    @ApiOperation(value = "技术职称系列库-添加")
    @PostMapping(value = "/add")
    public HttpResult<?> add(@RequestBody SpcyRsZck bean) {

        return HttpResultVo.HttpResultSave(spcyRsZckService.addZc(bean), "添加成功");
    }

    @Log(title = "技术职称系列库-编辑")
    @ApiOperation(value = "技术职称系列库-编辑")
    @PutMapping(value = "/edit")
    public HttpResult<?> edit(@RequestBody HashMap<String, String> buffer) throws InvocationTargetException, IllegalAccessException {

        spcyRsZckService.updatwZc(buffer);
        return HttpResult.ok("保存成功");
    }

    @Log(title = "技术职称系列库-删除")
    @ApiOperation(value = "技术职称系列库-删除")
    @DeleteMapping(value = "/delete")
    public HttpResult<?> delete(@RequestParam(value = "id",defaultValue = "") String id) {

        spcyRsZckService.deleteZc(id);
        return HttpResult.ok("删除成功");
    }

    @Log(title = "技术职称系列库-导入")
    @ApiOperation(value = "技术职称系列库-导入")
    @PostMapping(value = "impZckData")
    public HttpResult<?> impZckData(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx")) {
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");
        }

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_RS_ZCK_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            for (Map map : mapsList) {
                SpcyRsZck zck = new SpcyRsZck();
                BeanUtil.copyProperties(map, zck);
                zck.setId(GetUuIdUtils.ReplaceUuId());
                spcyRsZckService.save(zck);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }


    @Log(title = "技术职称系列库-导入模板")
    @ApiOperation(value = "技术职称系列库-导入模板")
    @GetMapping("/downZcTemplate")
    public void downZcTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("zcImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_RS_ZCK_XML, out);
        } catch (Exception e) {
            log.error("下载基本事项库模板错误-{}",e.getMessage());
            throw new BusinessException("下载基本事项库模板错误");
        }
    }


    @Log(title = "技术职称系列库-导出")
    @ApiOperation(value = "技术职称系列库-导出")
    @GetMapping("/exportZckData")
    public void exportZckData(@RequestParam(value = "ids",defaultValue = "")String ids,
                              SpcyRsZck query,
                              HttpServletResponse response){
        try {
            String name = "exportZck";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<Object> list = new ArrayList<>(); // 导出的数据

            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                List<String> idsList  = StringPatternUtils.getListByIds(ids);
                List<SpcyRsZck> spcyRsJbsxList = spcyRsZckService.listByIds(idsList);
                if (CollectionUtils.isNotEmpty(spcyRsJbsxList)){
                    for (SpcyRsZck e : spcyRsJbsxList){
                        list.add(e);
                    }
                }
            }else {
                LambdaQueryWrapper<SpcyRsZck> queryWrapper = new LambdaQueryWrapper();
                queryWrapper.like(StringUtils.isNotEmpty(query.getFjb()),SpcyRsZck::getFjb,query.getFjb());
                queryWrapper.like(StringUtils.isNotEmpty(query.getFzcxllx1()),SpcyRsZck::getFzcxllx1,query.getFzcxllx1());
                queryWrapper.like(StringUtils.isNotEmpty(query.getFzcxllx2()),SpcyRsZck::getFzcxllx2,query.getFzcxllx2());
                queryWrapper.like(StringUtils.isNotEmpty(query.getFzyjszg()),SpcyRsZck::getFzyjszg,query.getFzyjszg());
                queryWrapper.orderByAsc(SpcyRsZck::getForder);
                queryWrapper.orderByAsc(SpcyRsZck::getCreateTime);
                List<SpcyRsZck> listData = spcyRsZckService.list(queryWrapper);
                // 条件导出
                if (CollectionUtils.isNotEmpty(listData)){
                    for (SpcyRsZck e : listData){
                        list.add(e);
                    }
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_RS_ZCK_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出数据出错-{}",e.getMessage());
        }
    }
}
